use clap::{Parser, Subcommand};
use sudoku::{Difficulty, Sudoku};
use std::io::{self, BufRead};

mod dlx;
mod sudoku;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// 生成数独
    Generate {
        /// 难度级别
        #[arg(short, long, value_enum)]
        difficulty: Difficulty,
    },
    /// 验证数独
    Validate,
    /// 求解数独
    Solve,
}

fn main() {
    let cli = Cli::parse();
    let mut sudoku = Sudoku::new();

    match cli.command {
        Commands::Generate { difficulty } => {
            sudoku.generate(difficulty);
            sudoku.print();
        }
        Commands::Validate => {
            println!("请输入数独数据（每行数字用空格分隔，空单元格用 0 表示）：");
            let stdin = io::stdin();
            let mut input_data = Vec::new();
            for _ in 0..9 {
                let mut line = String::new();
                stdin.lock().read_line(&mut line).expect("读取输入失败");
                let row: Vec<u8> = line.split_whitespace()
                    .map(|s| s.parse().expect("无效的数字输入"))
                    .collect();
                input_data.push(row);
            }

            // 假设 Sudoku 结构体有一个从二维数组加载数独的方法
            if let Err(err) = sudoku.load_from_data(input_data) {
                println!("加载数独数据失败: {}", err);
                return;
            }

            println!("当前数独:");
            sudoku.print();

            // 增强验证逻辑
            match sudoku.validate() {
                Ok(_) => println!("验证结果: 有效 - 数独符合所有规则"),
                Err(err) => println!("验证结果: 无效 - {}", err),
            }
        },
        Commands::Solve => {
            println!("请输入需要求解的数独数据（每行数字用空格分隔，空单元格用 0 表示）：");
            let stdin = io::stdin();
            let mut input_data = Vec::new();
            for _ in 0..9 {
                let mut line = String::new();
                stdin.lock().read_line(&mut line).expect("读取输入失败");
                let row: Vec<u8> = line.split_whitespace()
                    .map(|s| s.parse().expect("无效的数字输入"))
                    .collect();
                input_data.push(row);
            }

            // 加载数独数据
            if let Err(err) = sudoku.load_from_data(input_data) {
                println!("加载数独数据失败: {}", err);
                return;
            }

            println!("输入的数独:");
            sudoku.print();

            println!("求解中...");
            match sudoku.solve() {
                true => {
                    println!("求解成功:");
                    sudoku.print();
                    
                    // 验证求解结果
                    match sudoku.validate() {
                        Ok(_) => println!("验证结果: 有效解"),
                        Err(err) => println!("警告: 求解结果无效 - {}", err),
                    }
                }
                false => println!("无解: 该数独无有效解"),
            }
        }
    }
}
